package com.ljc.service;

import com.ljc.dao.AttachmentDao;
import com.ljc.dao.DeviceContractDao;
import com.ljc.entity.Attachment;
import com.ljc.entity.DeviceContract;
import com.ljc.vo.DeviceContractSearch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class DeviceContractServiceImpl implements DeviceContractService{
    @Autowired
    private DeviceContractDao deviceContractDao;

    @Autowired
    private AttachmentDao attachmentDao;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void add(DeviceContract deviceContract) {
        deviceContractDao.add(deviceContract);
        int id = deviceContract.getId();
        List<Attachment> attachments = deviceContract.getAttachments();
        for (Attachment attachment : attachments) {
            attachment.setMainId(id);
            attachment.setType(2);  //2附件合同
        }
        attachmentDao.add(attachments);
    }

    @Override
    public List<DeviceContract> searchByUser(DeviceContractSearch search) {
        return deviceContractDao.searchByUser(search);
    }

    @Override
    public DeviceContract findOne(int id) {
        List<Attachment> byTypeAndMainId = attachmentDao.getByTypeAndMainId(2, id);
        DeviceContract one = deviceContractDao.findOne(id);
        one.setAttachments(byTypeAndMainId);
        return one;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void update(DeviceContract deviceContract) {
        deviceContractDao.update(deviceContract);
        List<Attachment> attachments = deviceContract.getAttachments();
        int id = deviceContract.getId();
        attachmentDao.deleteByContractId(id);
        if (attachments!=null && attachments.size()>0){
            for (Attachment attachment : attachments) {
                attachment.setMainId(id);
                attachment.setType(2);  //2附件合同
            }
            attachmentDao.add(attachments);
        }

    }

    @Override
    public void delete(int id) {
        deviceContractDao.delete(id);
        attachmentDao.deleteByContractId(id);
    }

    @Override
    public List<DeviceContract> searchByAdmit(DeviceContractSearch search) {
        return deviceContractDao.searchByAdmit(search);
    }
}
